# -*- coding: utf-8 -*-
#
#

# Must be at the beginning of the file
from __future__ import with_statement

import sys
from time import localtime, strftime
import os
import ConfigParser
import socket
import urllib, urlparse

# Symbian
import positioning
import sysinfo
import appuifw
import e32
import btsocket
import location

APP_NAME = 'YouLoc'
APP_VERSION = 0.4

"""
Tero Heino, whiz@iki.fi, 2009
"""

class YouLocUpdater(object):
    api_url = 'http://youloc.net/logger.php'

    def post(self, **kwargs):
	url = self.api_url + '?' + urllib.urlencode(kwargs)
	self._post_using_btsocket(url)

    def _post_using_urllib(self, url):
	u = urllib.urlopen(url)
        d = u.read()
        u.close()

    def _post_using_btsocket(self, url):
	u = urlparse.urlparse(url)
	s = btsocket.socket(btsocket.AF_INET, btsocket.SOCK_STREAM)
        s.connect(('youloc.net', 80))
        s.send("GET %s HTTP 1.1\nHost: %s\n\n" % (u.path+'?'+u.query, u.netloc))
	data = s.recv(1024)
	s.close()

# END class YouLocUpdater

class YouLocLocation(object):

    self __init__(self):
	self.position_data = None
	
	positioning.set_requestors([{"type":"service", "format":"application", "data":"YouLoc"}])
        positioning.position(course=1, satellites=0, interval=1000000, partial=1
	    callback=self._process_position_data)

    def has_fix(self):
        if self.position_data:
            data = self.position_data
            if "position" in data:
                if str(data['position'].get('latitude', 'nan')).lower() != "nan":
                    return True
        return False

    def _process_position_data(self, data):
        self.position_data = data

# END class YouLocLocation

class YouLoc(object):
    cfg_file = 'e:\\youloc.cfg'
    config = None
    t = None
    lock = None
    apo = None
    apid = None
    fix = False
    position_data = None
    previous_position_data = None
    gsm_cell = None

    def __init__ (self):
        self.config = ConfigParser.RawConfigParser()
	self.updater = YouLocUpdater()
        self.lock = e32.Ao_lock()
        appuifw.app.exit_key_handler = self.quit
        self.t = appuifw.Text()
        appuifw.app.body = self.t
        self.t.clear()

    def init_ui(self):
        appuifw.app.title = u'%s v%.1f' % (APP_NAME, APP_VERSION)
        appuifw.app.screen = 'large'
        appuifw.app.menu = [(u"Run configure", self.configure),(u"Quit", self.quit)]

    def read_config(self):
        if ( os.path.isfile(self.cfg_file) ):
            self.config.read(self.cfg_file)
            self.userkey = self.config.get('common', 'userkey')
            self.apid = self.config.getint('common', 'apid')
            if self.userkey == None or self.apid == None:
                self.configure()
            self.output(self.userkey)
            self.output(self.apid)
        else:
            self.configure()

    def configure(self):
        apid = None
        userkey = None

        apid = btsocket.select_access_point()
        auth_methods = [u"IMEI",u"USERKEY"]

        auth_method = appuifw.selection_list(choices=auth_methods , search_field=0)
        if auth_method == 0:
            userkey = unicode(sysinfo.imei())
        elif auth_method == 1:
            while userkey == None:
                userkey = appuifw.query(u"Your YouLoc userkey", "text")
        try:
            self.config.add_section('common')
            self.config.set('common', 'userkey', userkey)
            self.config.set('common', 'apid', apid)
            with open(self.cfg_file, 'wb') as configfile:
                self.config.write(configfile)

        except IOError, e:
            appuifw.note( u'Unable to write to file!', 'error' )

        self.apid = apid
        self.userkey = userkey

    def output(self, msg, clearscreen = False):
        """ Output formatted message wit"""
        if clearscreen:
            self.t.clear()
            self.t.add(u"%s\n--------\n" % strftime("%H:%M:%S", localtime() ) )
        self.t.add(u"%s\n" % msg)

    def run(self):
        self.read_config()
        self.init_ui()
        self.get_internets()
        self.get_satellites()
        self.output('%s v%.1f' % (APP_NAME, APP_VERSION))
        self.output("connecting..")
        while True:
            self.lock.wait()

        self.output(u"Finished..")


# latitude altitude vertical_accuracy longitude horizontal_accuracy





    def postData(self):

	# FIXME:
        btsocket.set_default_access_point(self.apo)
        socket.set_default_access_point(u'Sonera Internet')
	socket.setdefaulttimeout(10)

	lat = self.position_data['position']['latitude']
	lon = self.position_data['position']['longitude']
	alt = self.position_data['position']['altitude']
	speed = self.position_data['course']['speed']

	# FIXME:
	if self.gsm_cell != None:
            mcc = self.gsm_cell[0]
            mnc = self.gsm_cell[1]
            lac = self.gsm_cell[2]
            cid = self.gsm_cell[3]

	# Push data to web
	self.updater.post(
	    userkey=self.userkey, lat=lat, lon=lon, alt=alt, speed=speed
	)

	# Push data to display
        self.output("Latitude: %.2f\nLongitude: %.2f\nAltitude: %d\nSpeed: %d\n\n" % (lat,lon,alt,speed), True)
        if self.gsm_cell != None:
            self.output("CellID: %d\nMCC: %d\nMNC: %d\nLAC: %d\n" %(cid, mcc, mnc, lac))

        self.previous_position_data = self.position_data


    def quit (self):
        self.lock.signal()
        appuifw.app.set_exit()




if __name__ == "__main__":
    YL = YouLoc()
    YL.run()
